package excelv

import (
	"fmt"
	"gitee.com/git_public/vfaith/builtin/vault"
	"github.com/xuri/excelize/v2"
	"strconv"
)

// ExportExcel 处理返回值的一个方法
func ExportExcel(data *vault.TableMap) (*excelize.File, error) {

	// 创建一个新的Excel文件
	f := excelize.NewFile()

	// 设置工作表名称
	sheetName := "Sheet1"
	index, _ := f.NewSheet(sheetName)

	// 记录每一列的最大字符数
	maxCharWidth := make([]int, len(data.Headers))

	// 写入标题行
	for colIndex, header := range data.Headers {
		cell, err := excelize.CoordinatesToCellName(colIndex+1, 1)
		if err != nil {
			//http.Error(w, "Failed to convert coordinates to cell name", http.StatusInternalServerError)
			//return nil
			return f, err
		}
		_ = f.SetCellValue(sheetName, cell, header.Value)
		maxCharWidth[colIndex] = len(header.Value.(string))
	}

	// 写入数据行
	for rowIndex, row := range data.Rows {
		for colIndex, header := range data.Headers {
			cell, err := excelize.CoordinatesToCellName(colIndex+1, rowIndex+2)
			if err != nil {
				//http.Error(w, "Failed to convert coordinates to cell name", http.StatusInternalServerError)
				//return
				return f, err
			}

			// 获取值并判断是否为数字
			value := row[header.Key]
			var strValue string
			switch v := value.(type) {
			case int, int8, int16, int32, int64, float32, float64:
				// 设置数字格式单元格
				_ = f.SetCellValue(sheetName, cell, v)
				strValue = strconv.FormatInt(v.(int64), 10)
			case string:
				if num, err := strconv.ParseFloat(v, 64); err == nil {
					// 字符串转换为数字
					_ = f.SetCellValue(sheetName, cell, num)
					strValue = strconv.FormatFloat(num, 'f', -1, 64)
				} else {
					// 保持为字符串
					_ = f.SetCellValue(sheetName, cell, v)
					strValue = v
				}
			default:
				// 其他情况保持为字符串
				_ = f.SetCellValue(sheetName, cell, v)
				strValue = ""
			}

			// 更新列的最大字符数
			if len(strValue) > maxCharWidth[colIndex] {
				maxCharWidth[colIndex] = len(strValue)
			}
		}
	}

	// 设置单元格样式为居中
	style, _ := f.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
			Vertical:   "center",
		},
		Font: &excelize.Font{
			Family: "等线",
			Size:   12,
		},
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
		},
	})

	// 设置工作表网格线不显示
	showGridLines := false
	_ = f.SetSheetView(sheetName, 0, &excelize.ViewOptions{
		ShowGridLines: &showGridLines,
	})

	_ = f.SetCellStyle(sheetName, "A1", fmt.Sprintf("%s%d", string(rune('A'+len(data.Headers)-1)), len(data.Rows)+1), style)

	// 根据最大字符数设置列宽
	for colIndex, width := range maxCharWidth {
		column := string(rune('A' + colIndex))
		_ = f.SetColWidth(sheetName, column, column, float64(width)*1.5) // 增加一点宽度以适应内容
	}

	// 设置为活动工作表
	f.SetActiveSheet(index)

	return f, nil

	/*
		// 保存Excel文件
		if err := f.SaveAs("output.xlsx"); err != nil {
			log.Printf("Failed to save Excel file: %v", err)
		}
		packet.HandleHTML(w, "访问成功")
	*/

	/*
		// 设置HTTP头
		w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
		w.Header().Set("Content-Disposition", "attachment; filename=output.xlsx")

		// 将Excel文件写入HTTP响应
		if err := f.Write(w); err != nil {
			http.Error(w, "Failed to write excel file", http.StatusInternalServerError)
			return
		}

		fmt.Println("Excel file successfully created and sent!")
	*/
}
